﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.AutoUpdate;
using DWF.Studio.Custom;
using DWF.Studio.ISerivces;
using DWF.Studio.Models;
using DWF.Studio.Services;
using DWF.Studio.Share.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using WpfMessageBoxLibrary;

namespace DWF.Studio.Views
{
    /// <summary>
    /// WindowUpgrade.xaml 的交互逻辑
    /// </summary>
    public partial class WindowUpgrade
    {
        private ISysUpgradeService _sysUpgradeService = null;

        private IAppService _appService = null;

        private SysVersionInfo _lastestVersion = null;

        private bool isUpgrade = true;
        private bool isUpgradeOver = false;
        public WindowUpgrade()
        {
            InitializeComponent();

            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                init();
            }
        }

        private void init()
        {
            _appService = AppService.Instance;
            _sysUpgradeService = new SysUpgradeService(_appService);
            this.tbProductName.Text = AssemblyInfoHelper.AssemblyProduct;
        }

        private async void DialogWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var currentVer = new Version(AssemblyInfoHelper.AssemblyVersion);
            this.tbkCurrentVersion.Text = currentVer.ToString(3);

            try
            {
                _lastestVersion = await _sysUpgradeService.GetLastestVersionAsync();
            }
            catch (Exception ex)
            {
                DWF.Studio.Share.Log.LogHelper.Error(ex);
            }

            if (_lastestVersion != null)
            {
                var lastVer = new Version(_lastestVersion.Version);

                if (lastVer > currentVer)
                {
                    this.btnCancel.Visibility = Visibility.Hidden;
                    this.btnUpgrade.Visibility = Visibility.Visible;
                    this.btnCancelDownload.Visibility = Visibility.Hidden;
                }

                this.tbkLastestVersion.Text = lastVer.ToString(3);
                this.tbkPublicTime.Text = _lastestVersion.UpgradeTime.ToString("D", _appService.GetCurrentCultureInfo());
                this.tbPublicDescription.Text = _lastestVersion.Description;
            }
        }

        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private async void btnUpgrade_Click(object sender, RoutedEventArgs e)
        {
            if (_lastestVersion != null)
            {
                this.progressBar.Visibility = Visibility.Visible;
                this.btnUpgrade.Visibility = Visibility.Hidden;
                this.btnCancelDownload.Visibility = Visibility.Visible;

                UpdateProgressBarDelegate updateProgressBaDelegate = new UpdateProgressBarDelegate(progressBar.SetValue);

                try
                {
                    //WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_SysUpgrade"), this);//显示loading窗体
                    //this.IsEnabled = false;

                    isUpgrade = false;
                    var file = await _sysUpgradeService.DownloadPackageAsync(_lastestVersion.DownloadUrl,
                        (downloadedSize, totalSize) =>
                        {
                            if (!isUpgrade)
                            {
                                var progressValue = Convert.ToDouble(string.Format("{0:0.0}", Convert.ToDouble(downloadedSize) / Convert.ToDouble(totalSize) * 100));
                                Dispatcher.Invoke(updateProgressBaDelegate, DispatcherPriority.Background, new object[] { RangeBase.ValueProperty, progressValue });
                                //WindowLoading.SetMsg(progressValue);
                                if (progressValue >= 100)
                                    isUpgradeOver = true;
                            }
                        });
                    if (isUpgradeOver || !string.IsNullOrWhiteSpace(file))
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(1));
                        if (FileHelper.CheckFileExisting(file))
                        {
                            _sysUpgradeService.Upgrade(file);
                        }
                    }
                }
                finally
                {
                    isUpgrade = true;
                    this.btnCancelDownload.Visibility = Visibility.Hidden;
                    this.btnCancel.Visibility = Visibility.Hidden;
                    this.btnUpgrade.Visibility = Visibility.Visible;
                    //WindowLoading.CloseWindow();//关闭loading窗体
                }
            }
        }

        private delegate void UpdateProgressBarDelegate(DependencyProperty dp, object value);
        protected override void OnClosing(CancelEventArgs e)
        {
            if (!isUpgrade)
            {
                var msgProperties = new WpfMessageBoxProperties()
                {
                    Button = MessageBoxButton.YesNo,
                    ButtonYesText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Yes"),
                    ButtonNoText = LocalizationProvider.GetLocalizedString("MessageBox_Button_No"),
                    Image = MessageBoxImage.Question,
                    Text = LocalizationProvider.GetLocalizedString("WindowUpgrade_MessageBox_CloseWindowCancelDownload"),
                    Title = LocalizationProvider.GetLocalizedString("UCtrlDesignRegion_MsgBox_Caption_CloseApp_ExecutingNotice"),
                };

                Window owner = Window.GetWindow(this);
                MessageBoxResult dlgResult = WpfMessageBox.Show(owner, ref msgProperties);

                if (dlgResult == MessageBoxResult.No)
                {
                    e.Cancel = true;
                    return;
                }
                else if (dlgResult == MessageBoxResult.Yes)
                {
                    cancelDownloadUpgrade();
                    e.Cancel = false;
                }
            }
        }
        private void btnCancelDownload_Click(object sender, RoutedEventArgs e)
        {
            cancelDownloadUpgrade();
        }
        private void cancelDownloadUpgrade()
        {
            _sysUpgradeService.CancelDownload();
            isUpgrade = true;
            IsEnabled = false;
            this.Dispatcher.InvokeAsync(() =>
            {
                System.Threading.Thread.Sleep(1000);
                IsEnabled = true;
                this.progressBar.Visibility = Visibility.Hidden;
                this.btnCancelDownload.Visibility = Visibility.Hidden;
                this.btnUpgrade.Visibility = Visibility.Visible;

            }, DispatcherPriority.ApplicationIdle);
        }
    }
}
